/*
 view.go
 Created by hupfei on 2019-09-11
*/

package model

import (
	"database/sql"
	"github.com/jmoiron/sqlx"
	"zimuzu_cvn_web_api/config"
	. "zimuzu_cvn_web_api/pkg/e"
)

//source 1昨日充值数量 2昨日提现数量
func GetYesterdayCvntChanged(source int) (float64, error) {
	var cvnt sql.NullFloat64
	var err error
	if source == 1 {
		err = sqlx.Get(config.C.DB.DB, &cvnt, "SELECT IFNULL(sum(amount), 0.00) FROM cvn_log WHERE (source = ? or source = ?) AND create_time >= UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE) - INTERVAL 1 DAY) AND create_time < UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE))", LogSourceIn, LogSourceInnerIn)
	} else {
		err = sqlx.Get(config.C.DB.DB, &cvnt, "SELECT IFNULL(sum(ABS(amount)), 0.00) FROM cvn_log WHERE ((source = ? and withdraw_status = 2) or (source = ? and withdraw_status = 2)) AND create_time >= UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE) - INTERVAL 1 DAY) AND create_time < UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE))", LogSourceOut, LogSourceInnerOut)
	}
	if err == sql.ErrNoRows {
		err = nil
	}
	if err != nil {
		Log("err", "yesterdayRechargeCvnt 失败：", source, err.Error())
	}
	return cvnt.Float64, err
}

//1未提现总代币数量 2不可用总代币数量
func GetUnWithdrawCvnt(source int) (float64, error) {
	var cvnt sql.NullFloat64
	var err error
	if source == 1 {
		err = sqlx.Get(config.C.DB.DB, &cvnt, "SELECT sum(amount) FROM cvn_amount")
	} else {
		err = sqlx.Get(config.C.DB.DB, &cvnt, "SELECT sum(frozen_balance) FROM cvn_amount")
	}
	if err == sql.ErrNoRows {
		err = nil
	}
	if err != nil {
		Log("err", "GetUnWithdrawCvnt 失败：", source, err.Error())
	}
	return cvnt.Float64, err
}

//1大额转账人数（单笔超过10万用户） 2大额提现人数（单笔超过10万用户）
func GetLargeCvntChangedUserCount(source int) (int64, error) {
	var cvnt sql.NullInt64
	var err error
	if source == 1 {
		err = sqlx.Get(config.C.DB.DB, &cvnt, "SELECT COUNT(*) FROM (SELECT COUNT(*) FROM cvn_log WHERE ABS(amount) > 100000 AND (source = ? and status = 1) AND create_time > UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE)) GROUP BY uid) a", LogSourceInnerOut)
	} else {
		err = sqlx.Get(config.C.DB.DB, &cvnt, "SELECT COUNT(*) FROM (SELECT COUNT(*) FROM cvn_log WHERE ABS(amount) > 100000 AND (source = ? and status = 1) AND create_time > UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE)) GROUP BY uid) a", LogSourceOut)
	}
	if err == sql.ErrNoRows {
		err = nil
	}
	if err != nil {
		Log("err", "GetLargeCvntChangedUserCount 失败：", source, err.Error())
	}
	return cvnt.Int64, err
}

//获取source类型的今日cvn总和
func GetLogTodayCvntCount(source int) (float64, error) {
	var cvnt sql.NullFloat64
	err := sqlx.Get(config.C.DB.DB, &cvnt, "SELECT sum(ABS(amount)) FROM cvn_log WHERE source = ? AND create_time > UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE))", source)
	if err == sql.ErrNoRows {
		err = nil
	}
	if err != nil {
		Log("err", "GetLogCvntCount 失败：", source, err.Error())
	}
	return cvnt.Float64, err
}

//获取质押提取的cvnt
func GetTodayDrawCvntCount(source int) (float64, error) {
	var cvnt sql.NullFloat64
	err := sqlx.Get(config.C.DB.DB, &cvnt, "SELECT SUM(cvn) FROM cvn_user_draw_task WHERE type = ? AND status = 0 AND create_time > UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE)) order by create_time desc", source)
	if err == sql.ErrNoRows {
		err = nil
	}
	if err != nil {
		Log("err", "GetLogCvntCount 失败：", source, err.Error())
	}
	return cvnt.Float64, err
}

type CvntRankResponse struct {
	Name      string  `json:"name" db:"name"`
	Uid       int64   `json:"uid" db:"uid"`
	NodeCount int64   `json:"nodeCount" db:"nodeCount"`
	Cvnt      float64 `json:"cvnt" db:"cvnt"`
}

//获取cvnt排行榜
func GetCvntRankList() (list []CvntRankResponse, err error) {
	sqlStr := "SELECT a.uid AS uid, u.nickname AS NAME, (balance+ frozen_balance) AS cvnt, COUNT(b.id) AS nodeCount FROM " +
		" (SELECT * FROM cvn_amount WHERE `balance` > 1000 ) AS a LEFT JOIN mg_token as b on a.uid = b.belong_uid " +
		" INNER JOIN user as u on a.uid = u.uid where 1 group by cvnt desc limit 200"
	err = sqlx.Select(config.C.DB.DB, &list, sqlStr)
	if err != nil {
		Log("err", "GetCvntRankList 失败！", err.Error())
	}

	return list, err
}

type ViewUserResponse struct {
	TodayAdd int    `json:"todayAdd" db:"todayAdd"`
	YesAdd   int    `json:"yesterdayAdd" db:"yesterdayAdd"`
	Total    int    `json:"total" db:"total"`
	Active   int    `json:"active" db:"active"`
	Hold     int    `json:"hold" db:"hold"`
	Effect   int    `json:"effect" db:"effect"`
	Activate int    `json:"activate" db:"activate"`
	Rate     string `json:"rate" db:"rate"`
}

func GetUserViewData() (re ViewUserResponse, err error) {

	err = sqlx.Get(config.C.DB.DB, &re.YesAdd, "SELECT count(*) FROM user WHERE "+
		" create_time >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(),INTERVAL 1 DAY)) AND create_time < UNIX_TIMESTAMP(CURDATE())")
	if err != nil {
		re.YesAdd = 0
	}

	err = sqlx.Get(config.C.DB.DB, &re.TodayAdd, "SELECT count(*) FROM user WHERE create_time >= UNIX_TIMESTAMP(CURDATE())")
	if err != nil {
		re.TodayAdd = 0
	}

	err = sqlx.Get(config.C.DB.DB, &re.Total, "SELECT count(*) FROM user WHERE 1")
	if err != nil {
		re.Total = 0
	}

	err = sqlx.Get(config.C.DB.DB, &re.Active, "SELECT count(DISTINCT uid) FROM cvn_log WHERE source <> 1")
	if err != nil {
		re.Active = 0
	}

	err = sqlx.Get(config.C.DB.DB, &re.Hold, "SELECT count(*) FROM cvn_amount WHERE frozen_balance > 0")
	if err != nil {
		re.Hold = 0
	}

	err = sqlx.Get(config.C.DB.DB, &re.Effect, "SELECT count(*) FROM cvn_amount WHERE (balance + frozen_balance) > 100")
	if err != nil {
		re.Effect = 0
	}

	err = sqlx.Get(config.C.DB.DB, &re.Activate, "SELECT count(*) FROM user_wallet_address WHERE status = 1")
	if err != nil {
		re.Activate = 0
	}

	// 注册24小时有资产变动
	actUser := 0
	err = sqlx.Get(config.C.DB.DB, &actUser, "SELECT count(*) FROM cvn_log WHERE source <> 1 and "+
		" create_time >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(),INTERVAL 1 DAY)) AND uid in ("+
		" SELECT uid FROM user WHERE create_time >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(),INTERVAL 1 DAY)) "+
		" AND create_time < UNIX_TIMESTAMP(CURDATE()) )")
	if err != nil {
		re.Rate = "0.00"
	}
	if re.YesAdd > 0 {
		re.Rate = ParseString(float64(actUser)/float64(re.YesAdd), 2)
	} else {
		re.Rate = "0.00"
	}

	return
}

//新增节点
//1 pc 2linux 3router
//status 1 今日新增节点  2总共节点数
func GetTodayNewNode(source int, status int) (int64, error) {
	var count sql.NullInt64
	var err error
	if status == 1 {
		err = sqlx.Get(config.C.DB.DB, &count, "SELECT COUNT(*) FROM mg_node WHERE type = ? AND token_status > 1 AND"+
			" UNIX_TIMESTAMP(create_time) > UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE)) AND status = 1", source)
	} else {
		err = sqlx.Get(config.C.DB.DB, &count, "SELECT COUNT(*) FROM mg_node WHERE type = ? AND status = 1 AND token_status > 1", source)
	}
	if err == sql.ErrNoRows {
		err = nil
	}
	if err != nil {
		Log("err", "GetTodayNewNode 失败：", source, err.Error())
	}
	return count.Int64, err
}

//发放的cvnt
//1 pc 2linux 3router
//status 1 昨日  2总共
func GetCvntInfo(source int, status int) (float64, error) {
	var cvnt sql.NullFloat64
	var err error
	if status == 1 {
		err = sqlx.Get(config.C.DB.DB, &cvnt, "SELECT sum(cvn) FROM mg_node_payment WHERE type = ? AND date = DATE_SUB(CURDATE(),INTERVAL 1 DAY) AND status = 1", source)
	} else {
		err = sqlx.Get(config.C.DB.DB, &cvnt, "SELECT sum(cvn) FROM mg_node_payment WHERE type = ? AND status = 1", source)
	}
	if err == sql.ErrNoRows {
		err = nil
	}
	if err != nil {
		Log("err", "GetCvntInfo 失败：", source, err.Error())
	}
	return cvnt.Float64, err
}
